// pages/promotePage/index.js
const common = require('../../utils/common');
const api = require('../../services/request');
const wxp = require('../../utils/wxp.js');
const env = require('../../utils/env');
const userUtils = require("../../utils/user");
const {
  shopGenerate,
  getShopInfo
} = require('../../services/shop');

// 方法定义
function createRpx2px() {
  const {
    windowWidth
  } = wx.getSystemInfoSync();

  return function (rpx) {
    return windowWidth / 750 * rpx;
  }
}

//rpx转换
const rpx2px = createRpx2px();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 分享
    shareMessageInfo: {
      code: '',
      token: ''
    },
    isGroupOwner: 0,
    imageInfo: {
      posterUrl: '',
      longPressUrl: ''
    },
    shopInfo: {},
    postInfo: {
      icon: '',
      filePath: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu({});
    // 初始化数据
    this.initData(options);
  },

  // 初始化数据
  initData(options) {
    // 分享进来
    if (options.token) {
      this.setData({
        shareMessageInfo: {
          ...this.data.shareMessageInfo,
          code: options.code,
          token: options.token
        }
      });
    } else {
      this.setData({
        shareMessageInfo: {
          ...this.data.shareMessageInfo,
          code: userUtils.getCode(),
          token: userUtils.getToken()
        }
      });
    }
    
    // 邀请团长标记
    if (options.isGroupOwner) {
      this.setData({
        isGroupOwner: parseInt(options.isGroupOwner),
      })
    } else {
      this.setData({
        isGroupOwner: 1,
      })
    }
    // 获取店铺信息
    this.requesgtoGetShopInfo({
      code: this.data.shareMessageInfo.code,
      token: this.data.shareMessageInfo.token
    });
    //获取海报连接
    this.getShopPoster({
      code: this.data.shareMessageInfo.code,
      token: this.data.shareMessageInfo.token
    });
  },

  //获取店铺信息
  requesgtoGetShopInfo({
    code,
    token
  } = {}) {
    // 获取店铺信息
    api.request("POST", '/shop/info', {}, code, token).then(res => {
      this.setData({
        shopInfo: res.data
      });
      if (this.data.isGroupOwner) {
        wx.setNavigationBarTitle({
          title: '邀请你成为团长'
        });
      } else {
        wx.setNavigationBarTitle({
          title: '好想你心选'
        });
      }
    }).catch(err => {
      common.log(err);
    })
  },

  //获取海报连接
  getShopPoster({
    code,
    token
  } = {}) {
    // 获取海报连接
    let params = {};
    if (this.data.isGroupOwner) {
      params = {
        path: "pages/tobeTzFirstStep/tobeTzFirstStep",
        platform: '1', //c端
        type: '1', //邀请成为团长
      }
    } else {
      params = {
        path: 'pages/index/index',
        platform: '1', //c端
        type: '3', //邀请下单领红包
      }
    }
    api.request("POST", '/shop/generate', params, code, token).then(res => {
      // 打开分享
      wx.showShareMenu({});
      this.setData({
        postInfo: {
          ...this.data.postInfo,
          ...{
            icon: res.data
          }
        }
      });
    }).catch(err => {
      common.log(err);
    })
  },

  // 保存图片
  saveImage() {
    if (this.data.postSrc) {
      this.saveToAlbum(this.data.postSrc);
      return
    }
    wxp.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 361,
      height: 584.5,
      destWidth: 722,
      destHeight: 1169,
      canvasId: 'promote-canvas',
      fileType: 'jpg',
      quality: 1,
    }, this).then(res => {
      this.setData({
        postSrc: res.tempFilePath
      })
      this.saveToAlbum(res.tempFilePath);
    }).catch(err => {
      common.log(err);
    });
  },

  //保存到相册
  saveToAlbum: function (filePath) {
    //获取权限
    if (wx.saveImageToPhotosAlbum) {
      wxp.getSetting().then(res => {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wxp.authorize({
            scope: 'scope.writePhotosAlbum'
          }).then(res => {
            //直接保存
            this.savePageImageToPhotosAlbum(filePath);
          }).catch(res => {
            //拒绝授权,打开设置
            this.openPhotosAlbumSetting(res);
          });
        } else {
          //3.写入相册
          this.savePageImageToPhotosAlbum(filePath);
        }
      }).catch(res => {
        common.log(res);
      });
    } else {
      common.showModal("当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。");
    }
  },

  //提示打开相册权限
  openPhotosAlbumSetting: function (res) {
    //授权拒绝
    var firstAuthDeny = res.errMsg.indexOf("fail auth deny") != -1;
    if (firstAuthDeny) return;
    //提示打开设置
    common.showModal("亲，我们未获得您的相册授权，即将打开设置", {}, () => {
      wx.openSetting({
        success: res => {
          var isOpenWriteAuth = res.authSetting['scope.writePhotosAlbum'];
          // 选择自提点
          if (isOpenWriteAuth) {
            this.savePageImageToPhotosAlbum(this.data.pageFilePath);
          }
        }
      })
    })
  },

  //保存海报图片到相册
  savePageImageToPhotosAlbum: function (tempFilePath) {
    wx.saveImageToPhotosAlbum({
      filePath: tempFilePath,
      success: res => {
        common.showModal("海报保存成功！");
      }
    });
  },

  // 绘制分享页面
  drawSharePage() {
    //定义变量
    const caW = rpx2px(722);
    var y = 0;
    const ctx = wx.createCanvasContext('promote-canvas', this);
    //1.首先清空画布
    ctx.clearRect(0, 0, rpx2px(722), rpx2px(1169));
    //1.绘制背景色
    ctx.save();
    // 绘制背景色圆角
    common.roundRect(ctx, 0, 0, caW, rpx2px(1169), rpx2px(0), "#fff");
    //绘制图片
    y = 0;
    ctx.drawImage(this.data.imageInfo.posterUrl, rpx2px(18), y, rpx2px(686), rpx2px(956));
    // 绘制长按图片
    y += rpx2px(956);
    ctx.drawImage(this.data.imageInfo.longPressUrl, 0, y, rpx2px(454), rpx2px(213));
    // 绘制太阳码
    y += rpx2px(16);
    ctx.drawImage(this.data.imageInfo.posterUrl, rpx2px(497.5), y, rpx2px(181), rpx2px(181));
    //绘制
    ctx.draw();
  },

  // 保存海报
  onSavePoster() {
    if (this.data.postInfo.filePath) {
      this.saveToAlbum(this.data.postInfo.filePath);
      return
    }
    common.wxDownloadFile(this.data.postInfo.icon).then(res => {
      this.setData({
        postInfo: {
          ...this.data.postInfo,
          ...{
            filePath: res
          }
        }
      })
      this.saveToAlbum(this.data.postInfo.filePath);
    }).catch(err => {
      common.log(err);
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // this.drawSharePage();
  },

  // 我要做团长
  onTobeGroupOwner() {
    wxp.navigateToMiniProgram({
      appId: env.cAppIdKey,
      path: 'pages/tobeTzFirstStep/tobeTzFirstStep?scene=' + this.data.shopInfo.id,
      envVersion: env.status == 0 ? 'trial' : 'release'
    }).then(res => {
      common.log("打开小程序成功")
    }).catch(err => {});
  },

  // 我要抢货
  onToBuy() {
    wxp.navigateToMiniProgram({
      appId: env.cAppIdKey,
      path: 'pages/index/index?scene=' + this.data.shopInfo.id,
      envVersion: env.status == 0 ? 'trial' : 'release'
    }).then(res => {
      common.log("打开小程序成功")
    }).catch(err => {});
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return this.shareAppMessage();
  },

  //获取分享的AppMessage
  shareAppMessage: function () {
    let tmpPath = '/pages/promotePage/index?token=' + this.data.shareMessageInfo.token + '&code=' + this.data.shareMessageInfo.code + "&isGroupOwner=" + this.data.isGroupOwner;
    return {
      title: this.data.isGroupOwner ? '邀请你成为团长' : '为你挑选优质好货',
      path: tmpPath,
      imageUrl: this.data.postInfo.icon
    }
  },
})
